<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users extends My_Controller{
    var $error=null;
    function __construct(){
        parent::__construct("user");
        $this->load->model('user_model');
        $this->load->model('authentication_model');
        $this->load->model('utility_model');
    }
    public function logout()
    {
        $this->authentication_model->logout();
    }    
        public function viewCreateUser()
    {       
        $this->data['dt'] = array('0' => array(
                'id' => '',
                'title' => '',
                'summary' => '',
                'content' => ''));
        $this->data['danhsachquyen']=$this->indsQuyen();
        if($this->error!=NULL) echo "<script>alert('".$this->error."')</script>";
        $this->template->parse_view('main_content', 'user/create.html', $this->data);
        $this->template->parse_view('info_content', 'template/info_content_create.html',
            $this->data);
        // Render template
        $this->template->render();
    }
    public function getIdQuyen($ten_quyen)
    {
        echo  $this->user_model->getIdQuyen($ten_quyen);
    }
    public function viewEditUser($id=null)
    {
        $result=$this->user_model->thongtinUser($id);
        foreach($result as $row);
        $this->data['capdo']=$row['capnguoidung'];
        $this->data['dt'] = 
        array('0' => array(
                'user' => $row['ten_nguoidung'],
                'name' => $row['tenthat_nguoidung'],
                'id' => $row['id_nguoidung']));
        $listQuyen=$this->user_model->getListQuyen($id);
        $this->data['danhsachquyen']=$this->indsQuyen($listQuyen);
        if($this->error!=NULL) echo "<script>alert('".$this->error."')</script>";
        $this->template->parse_view('main_content', 'user/edit.html', $this->data);
        $this->template->parse_view('info_content', 'template/info_content_create.html',
            $this->data);
        // Render template
        $this->template->render();
    }
    public function doCreateUser()
    {
        $this->load->library('form_validation');
		$this->form_validation->set_rules('user', 'Tên tài khoản', 'xss_clean|required|min_length[5]|max_length[150]');
        $this->form_validation->set_rules('password', 'Password', 'xss_clean|required|min_length[5]|max_length[150]');
        $this->form_validation->set_rules('repassword', 'Xác nhận password', 'xss_clean|required|min_length[5]|max_length[150]');
        $this->form_validation->set_rules('name', 'Tên đầy đủ', 'xss_clean|required|min_length[5]|max_length[150]');
        if($this->form_validation->run())
        {
        $user = $this->security->xss_clean($this->input->post('user'));
		$password = $this->security->xss_clean($this->input->post('password'));
		$repassword = $this->security->xss_clean($this->input->post('repassword'));
		$name = $this->security->xss_clean($this->input->post('name'));
        $capnguoidung = $this->security->xss_clean($this->input->post('capnguoidung'));
        $dsQuyen = $this->security->xss_clean($this->input->post('dsQuyen'));
        //echo"<pre>";
//        print_r($dsQuyen);
//        echo "</pre>";
        $checkExist=$this->utility_model->checkExist($user,'ten_nguoidung','nguoidung');
            if($checkExist=="false_value") 
                {
                    $this->error="Người dùng đã tồn tại!";
                    $this->viewCreateVideo();
                    return;
                }
            else if($checkExist=="false_field")
                {
                    $this->error="Trường không tồn tại!";
                    $this->viewCreateVideo();
                    return;
                }
        if($password!=$repassword) 
            {
                $this->error="Password không khớp nhau!";
                $this->viewCreateUser();      
            } else
                {
                 $result=$this->user_model->them_user($capnguoidung,$user,$password,$name);   
                 if($result) 
                    {
                        $rs=$this->user_model->themQuyen($result,$dsQuyen);
                        if($rs)
                            {
                             $this->error="Thêm thành công tài khoản $user!";
                             $this->viewCreateUser();   
                            }  
                    } else
                        {
                            $this->error="Lỗi khi thêm vào CSDL!";
                            $this->viewCreateUser();  
                        }
                }
        } else 
        {
            $this->viewCreateUser();   
        }
    }
    public function indsQuyen($listQuyen=null)
    {
        $quyenVideo=$this->user_model->dsQuyen('video');
        $quyenTintuc= $this->user_model->dsQuyen('tintuc');
        $quyenChuyenmuc = $this->user_model->dsQuyen('chuyenmuc');
        $quyenMenu = $this->user_model->dsQuyen('menu');
        $quyenQuangcao = $this->user_model->dsQuyen('quangcao');
        $quyenNguoidung = $this->user_model->dsQuyen('nguoidung');
        $ketqua="";
        $ketqua=$ketqua."<table>
                    <tr>
                        <td><label>Video</label></td>";
                        foreach($quyenVideo as $row)
                            {
                                if($this->checkQuyen($row->id_quyen,$listQuyen)) $check=true; else $check=false;
                                $ketqua=$ketqua."<td>".form_checkbox('dsQuyen[]', $row->id_quyen,$check).$row->chuthich_quyen."</td>";
                            }
         $ketqua=$ketqua."</tr>
                     <tr>
                        <td><label>Tin tức</label></td>";
                        foreach($quyenTintuc as $row)
                            {
                                //if($this->checkQuyen($row->id_quyen,$listQuyen)) $check=true; else $check=false;
                                $ketqua=$ketqua."<td>".form_checkbox('dsQuyen[]', $row->id_quyen,$this->checkQuyen($row->id_quyen,$listQuyen)).$row->chuthich_quyen."</td>";
                            }
         $ketqua=$ketqua."</tr>
                     <tr>
                        <td><label>Chuyên mục</label></td>";
                        foreach($quyenChuyenmuc as $row)
                            {
                                if($this->checkQuyen($row->id_quyen,$listQuyen)) $check=true; else $check=false;
                                $ketqua=$ketqua."<td>".form_checkbox('dsQuyen[]', $row->id_quyen,$check).$row->chuthich_quyen."</td>";
                            }
         $ketqua=$ketqua."</tr>
                     <tr>
                        <td><label>Menu</label></td>";
                        foreach($quyenMenu as $row)
                            {
                                if($this->checkQuyen($row->id_quyen,$listQuyen)) $check=true; else $check=false;
                                $ketqua=$ketqua."<td>".form_checkbox('dsQuyen[]', $row->id_quyen,$check).$row->chuthich_quyen."</td>";
                            }
         $ketqua=$ketqua."</tr>
                     <tr>
                        <td><label>Quảng cáo</label></td>";
                        foreach($quyenQuangcao as $row)
                            {
                                if($this->checkQuyen($row->id_quyen,$listQuyen)) $check=true; else $check=false;
                                $ketqua=$ketqua."<td>".form_checkbox('dsQuyen[]', $row->id_quyen,$check).$row->chuthich_quyen."</td>";
                            }
         $ketqua=$ketqua."</tr>
                     <tr>
                        <td><label>Người dùng</label></td>";
                        foreach($quyenNguoidung as $row)
                            {
                                if($this->checkQuyen($row->id_quyen,$listQuyen)) $check=true; else $check=false;
                                $ketqua=$ketqua."<td>".form_checkbox('dsQuyen[]', $row->id_quyen,$check).$row->chuthich_quyen."</td>";
                            }
         $ketqua=$ketqua."</tr>
                </table>";
         return $ketqua;
    }
    public function checkQuyen($quyen,$listQuyen)
        {
            if($listQuyen==null) return FALSE;
            foreach($listQuyen as $row)
                {
                    if($row['id_quyen']==$quyen) return TRUE;
                }
            return FALSE;
        }
    public function doEditUser()
    {
        $id = $this->security->xss_clean($this->input->post('id'));
        $this->load->library('form_validation');
		$this->form_validation->set_rules('user', 'Tên tài khoản', 'xss_clean|required|min_length[5]|max_length[150]');
        $this->form_validation->set_rules('password', 'Password', 'xss_clean|required|min_length[5]|max_length[150]');
        $this->form_validation->set_rules('repassword', 'Xác nhận password', 'xss_clean|required|min_length[5]|max_length[150]');
        $this->form_validation->set_rules('name', 'Tên đầy đủ', 'xss_clean|required|min_length[5]|max_length[150]');
        if($this->form_validation->run())
        {
        $user = $this->security->xss_clean($this->input->post('user'));
		$password = $this->security->xss_clean($this->input->post('password'));
		$repassword = $this->security->xss_clean($this->input->post('repassword'));
		$name = $this->security->xss_clean($this->input->post('name'));
        $capnguoidung = $this->security->xss_clean($this->input->post('capnguoidung'));
        $dsQuyen = $this->security->xss_clean($this->input->post('dsQuyen'));
        if($password!=$repassword) 
            {
                $this->error="Password không khớp nhau!";
                $this->viewEditUser($id);      
            } else
                {
                 $result=$this->user_model->sua_user($id,$capnguoidung,$user,$password,$name);   
                 if($result) 
                    {
                        $this->user_model->deleteQuyen($id);
                        $rs=$this->user_model->themQuyen($id,$dsQuyen);
                        $this->error="Thay đổi tài khoản $user thành công!";
                         $this->viewEditUser($id);  
                    } else
                        {
                            $this->error="Lỗi khi update vào CSDL!";
                            $this->viewEditUser($id);  
                        }
                }
        } else 
        {
            $this->viewEditUser($id);   
        }
    }
    public function doDeleteUser($id)
    {
        $result=$this->user_model->xoa_user($id);
        if($result) 
            {
                $this->error="Xóa thành công!";
            } else $this->error="Lỗi xóa user!";
            $this->viewAllUser();
    }
	public function viewAllUser()
    {
        $this->data = array();
        if($this->error!=NULL) echo "<script>alert('".$this->error."')</script>";
        $this->template->parse_view('main_content', 'user/table.html', $this->data);
        // Render template
        $this->template->render();
    }
    public function getDataTable()
    {
			/* Indexed column (used for fast and accurate table cardinality) */
		    $sIndexColumn = "ID";
		    // DB table to use
		    $sTable = 'menu';
		    $iDisplayStart = $this->input->get_post('iDisplayStart', true);
		    $iDisplayLength = $this->input->get_post('iDisplayLength', true);
		    $iSortCol_0 = $this->input->get_post('iSortCol_0', true);
		    $iSortingCols = $this->input->get_post('iSortingCols', true);
		    $sSearch = $this->input->get_post('sSearch', true);
		    $sEcho = $this->input->get_post('sEcho', true);
		    $_aColumns=array('id_nguoidung','tenthat_nguoidung','ten_nguoidung','capnguoidung','trangthai_nguoidung');
			 // Paging
		    if(isset($iDisplayStart) && $iDisplayLength != '-1' && $iDisplayLength != '0')
		    {
		        $this->db->limit($this->db->escape_str($iDisplayLength), $this->db->escape_str($iDisplayStart));
		    }
			// Ordering
		    if(isset($iSortCol_0))
		    {
		        for($i=0; $i<intval($iSortingCols); $i++)
		        {
		            $iSortCol = $this->input->get_post('iSortCol_'.$i, true);
		            $bSortable = $this->input->get_post('bSortable_'.intval($iSortCol), true);
		            $sSortDir = $this->input->get_post('sSortDir_'.$i, true);
		
		            if($bSortable == 'true')
		            {
		                $this->db->order_by($_aColumns[intval($this->db->escape_str($iSortCol))], $this->db->escape_str($sSortDir));
		            }
		        }
		    }
			if(isset($sSearch) && !empty($sSearch))
		    {
		        for($i=0; $i<count($_aColumns); $i++)
		        {
		            $bSearchable = $this->input->get_post('bSearchable_'.$i, true);
		
		            // Individual column filtering
		            if(isset($bSearchable) && $bSearchable == 'true')
		            {
		                $this->db->or_like($_aColumns[$i], $this->db->escape_like_str($sSearch));
		            }
		        }
		    }
		    // Select Data
		    $this->db->select('id_nguoidung,tenthat_nguoidung,ten_nguoidung,capnguoidung,trangthai_nguoidung');
			$rResult = $this->db->get('nguoidung');
		    $this->db->select('FOUND_ROWS() AS found_rows');
		    $iFilteredTotal = $this->db->get()->row()->found_rows;
		    // Total data set length
    		$iTotal = $this->db->count_all($sTable);
		    // Output
		    $output = array(
		        'sEcho' => intval($sEcho),
		        'iTotalRecords' => $iTotal,
		        'iTotalDisplayRecords' => $iFilteredTotal,
		        'aaData' => array()
		    );
            foreach($rResult->result_array() as $hang){
                $row=array();
                $id=$hang['id_nguoidung'];
                $linkSua=site_url("users/viewEditUser/$id");
                $linkXoa=site_url("users/doDeleteUser/$id");
                $confirm="submitLink()";
                $sua="<a href=$linkSua>Sửa</a>";
                $xoa="<a href=$linkXoa onclick='return $confirm'>Xóa</a>"; 
                $row[]=$hang['tenthat_nguoidung'];
                $row[]=$hang['ten_nguoidung'];
                if($hang['capnguoidung']==3) $capdo="Admin"; else if($hang['capnguoidung']==2)$capdo="Mod"; else $capdo="BTV";
                $row[]=$capdo;
                if($hang['trangthai_nguoidung']==1) $trangthai="Đã kích hoạt"; else $trangthai="Chưa kích hoạt";
                $row[]=$trangthai;
                $row[]=$sua;
                $row[]=$xoa;
                $output['aaData'][]=$row;
            }
			//echo "<pre>";
			//print_r($output);
			//echo "</pre>";
			echo json_encode( $output );
    }
}
?>
